package com.whfc.hdc.redis.impl;

import com.whfc.common.util.JSONUtil;
import com.whfc.hdc.dto.AppDeviceDTO;
import com.whfc.hdc.redis.DeviceRedisDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2020/9/24 18:16
 */
@Repository
public class DeviceRedisDaoImpl implements DeviceRedisDao {

    private static final String DEVICE_CACHE_ID = "device-cache-id";

    private static final String DEVICE_CACHE_SN = "device-cache-sn";

    private static final String DEVICE_CACHE_CODE = "device-cache-code";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void set(AppDeviceDTO deviceDTO) {
        if (deviceDTO == null) {
            return;
        }

        String deviceId = String.valueOf(deviceDTO.getId());
        String sn = deviceDTO.getSn();
        String code = deviceDTO.getCode();

        //清楚旧缓存
        AppDeviceDTO oldDeviceDTO = this.getById(deviceDTO.getId());
        if (oldDeviceDTO != null) {
            this.del(oldDeviceDTO);
        }

        //加入新缓存
        redisTemplate.opsForHash().put(DEVICE_CACHE_ID, deviceId, JSONUtil.toString(deviceDTO));
        redisTemplate.opsForHash().put(DEVICE_CACHE_SN, sn, JSONUtil.toString(deviceDTO));
        redisTemplate.opsForHash().put(DEVICE_CACHE_CODE, code, JSONUtil.toString(deviceDTO));
    }

    @Override
    public AppDeviceDTO getById(Integer deviceId) {

        String value = (String) redisTemplate.opsForHash().get(DEVICE_CACHE_ID, String.valueOf(deviceId));
        if (!StringUtils.isEmpty(value)) {
            return JSONUtil.parseObject(value, AppDeviceDTO.class);
        }
        return null;
    }

    @Override
    public AppDeviceDTO getBySn(String sn) {
        String value = (String) redisTemplate.opsForHash().get(DEVICE_CACHE_SN, sn);
        if (!StringUtils.isEmpty(value)) {
            return JSONUtil.parseObject(value, AppDeviceDTO.class);
        }
        return null;
    }

    @Override
    public AppDeviceDTO getByCode(String code) {
        String value = (String) redisTemplate.opsForHash().get(DEVICE_CACHE_CODE, code);
        if (!StringUtils.isEmpty(value)) {
            return JSONUtil.parseObject(value, AppDeviceDTO.class);
        }
        return null;
    }

    @Override
    public void del(AppDeviceDTO deviceDTO) {

        String deviceId = String.valueOf(deviceDTO.getId());
        String sn = deviceDTO.getSn();
        String code = deviceDTO.getCode();

        redisTemplate.opsForHash().delete(DEVICE_CACHE_ID, deviceId);
        redisTemplate.opsForHash().delete(DEVICE_CACHE_SN, sn);
        redisTemplate.opsForHash().delete(DEVICE_CACHE_CODE, code);
    }

}
